import { createApp, h, resolveComponent } from 'vue';
import usePortal from '../use/usePortal.js';
import LoadingBar from './LoadingBar.js';

const duration = 800;
let timer;
let bar;
function clearTimer() {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
}
function hide() {
  setTimeout(() => {
    update({
      show: false
    });
    setTimeout(() => {
      update({
        percent: 0
      });
    }, 200);
  }, duration);
}
function update(options) {
  bar.update(options);
}
function LoadingBarFn() {
  const ele = usePortal('cm-loading-bar-portal', 'cm-loading-bar-portal');
  createApp({
    components: {
      LoadingBar
    },
    render() {
      return h(resolveComponent('LoadingBar'), {
        ref: el => {
          bar = el;
        }
      });
    }
  }).mount(ele);
  return {
    start() {
      if (timer) return;
      let percent = 0;
      update({
        percent: percent,
        status: 'success',
        show: true
      });
      timer = setInterval(() => {
        percent += Math.floor(Math.random() * 3 + 1);
        if (percent > 95) {
          clearTimer();
        }
        update({
          percent: percent,
          status: 'success',
          show: true
        });
      }, 200);
    },
    finish() {
      clearTimer();
      update({
        percent: 100,
        status: 'success',
        show: true
      });
      hide();
    },
    error() {
      clearTimer();
      update({
        percent: 100,
        status: 'error',
        show: true
      });
      hide();
    }
  };
}
const loadingBar = LoadingBarFn();

export { loadingBar };
